/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.cef.core.data;

import com.inspur.edp.cef.api.ICefValueGetter;
import com.inspur.edp.cef.api.ValueGetterConfig;
import com.inspur.edp.cef.entity.condition.SortCondition;
import com.inspur.edp.cef.entity.condition.SortType;
import com.inspur.edp.cef.entity.entity.IEntityData;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import java.util.Comparator;
import java.util.List;
import org.springframework.util.comparator.Comparators;

class EntityDataCollectionComparator implements Comparator<IEntityData> {

  private static ICefValueGetter valueGetter = SpringBeanUtils.getBean(ICefValueGetter.class);
  private static ValueGetterConfig valueGetterConfig = ValueGetterConfig.builder()
      .associationValue(true).singleValueUdt(true).build();

  private final List<SortCondition> sorts;

  public EntityDataCollectionComparator(List<SortCondition> sorts) {
    this.sorts = sorts;
  }

  @Override
  public int compare(IEntityData o1, IEntityData o2) {
    for (SortCondition sort : sorts) {
      Object v1 = valueGetter.getValue(o1, sort.getSortField(), valueGetterConfig);
      Object v2 = valueGetter.getValue(o2, sort.getSortField(), valueGetterConfig);

      if ((v1 == null || v1 instanceof Comparable) && (v2 == null || v2 instanceof Comparable)) {
        int compare = Comparators.nullsLow().compare(v1, v2);
        if(compare == 0) {
          continue;
        } else {
          return bySortType(sort.getSortType(), compare);
        }
      }
    }
    return 0;
  }

  private final static int bySortType(SortType type, int value) {
    return type == SortType.Asc ? value : Math.negateExact(value);
  }
}
